package a12_图论;

import netscape.javascript.JSUtil;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * <p>
 * a07_岛屿的最大面积
 * </p>
 *
 * @author flyduck
 * @since 2025/3/26
 */
public class a07_岛屿的最大面积 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int rows = scanner.nextInt();
        int cols = scanner.nextInt();

        int[][] grid = new int[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                grid[i][j] = scanner.nextInt();
            }
        }

        int maxArea = 0;
        boolean[][] visited = new boolean[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if(grid[i][j] == 1 && !visited[i][j]){//没有访问过的陆地
                    area = 0;
                    //标记当前节点已经访问
                    visited[i][j] = true;
                    //标记邻居已经访问
                    dfs(grid,visited,i,j);
                    //计算总面积
                    maxArea = Math.max(maxArea, area + 1);
                }
            }
        }
        System.out.println(maxArea);
    }

    public static final int[][] dirs = new int[][]{{0,1},{1,0},{-1,0},{0,-1}};

    public static int area = 0;

    private static int dfs(int[][] grid, boolean[][] visited, int x, int y) {
        for (int[] dir : dirs) {
            int nextX = x + dir[0];
            int nextY = y + dir[1];
            if(nextX >= 0 && nextX < grid.length && nextY >= 0 && nextY < grid[0].length){
                if(grid[nextX][nextY] == 1 && !visited[nextX][nextY]){
                    area++;
                    visited[nextX][nextY] = true;
                    dfs(grid, visited, nextX, nextY);
                }
            }
        }
        return area;
    }

    private static int bfs(int[][] grid, boolean[][] visited, int x, int y) {
        int area = 0;

        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{x,y});

        while (!queue.isEmpty()) {
            int[] poll = queue.poll();
            for (int[] dir : dirs) {
                int nextX = poll[0] + dir[0];
                int nextY = poll[1] + dir[1];
                if(nextX >= 0 && nextX < grid.length && nextY >= 0 && nextY < grid[0].length){
                    if(grid[nextX][nextY] == 1 && !visited[nextX][nextY]){
                        area++;
                        visited[nextX][nextY] = true;
                        queue.add(new int[]{nextX,nextY});
                    }
                }
            }
        }
        return area;

    }
}
